<!--suppress HtmlUnknownTag -->
<script setup>
import Card from "@/components/Card.vue";
import {Message, Refresh, Select, User} from "@element-plus/icons-vue";
import {useStore} from "@/store";
import {computed, onMounted, reactive, ref} from "vue";
import {accessHeader} from "@/net";
import {ElMessage} from "element-plus";
import axios from "axios";
import {getAskCode, getUserDetail, saveUserDetail, userModifyEmail} from "@/api/user";

const store = useStore()
const registerTime = computed(() => new Date(store.user.registerTime).toLocaleString());

const baseFormRef = ref()
const emailFormRef = ref()
const desc = ref('')
const baseForm = reactive({
    username: '',
    gender: 1,
    phone: '',
    qq: '',
    wx: '',
    desc: ''
})
const emailForm = reactive({
    email: '',
    code: ''
})
const loading = reactive({
    form: true,
    base: false
})
const coldTime = ref(0)
const isEmailValid = ref(true)
const onValidate = (prop, isValid) => {
    if (prop === 'email') {
        isEmailValid.value = isValid
    }
}

const validateUsername = (_, value, callback) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
        callback(new Error('用户名不能包含特殊字符，只能是中文/英文'))
    } else {
        callback()
    }
}

const rules = {
    username: [
        {validator: validateUsername, trigger: ['blur', 'change']},
        {min: 2, max: 10, message: '用户名的长度必须在2-10个字符之间', trigger: ['blur', 'change']},
    ], email: [
        {required: true, message: '请输入邮件地址', trigger: 'blur'},
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
    ]
}

function saveDetails() {
    baseFormRef.value.validate(isValid => {
        if (isValid) {
            loading.base = true
            saveUserDetail(baseForm, () => {
                ElMessage.success('修改成功')
                store.user.username = baseForm.username
                desc.value = baseForm.desc
                loading.base = false
            }, message => {
                ElMessage.warning(message)
                loading.base = false
            })
        }
    })
}

function sendEmailCode() {
    emailFormRef.value.validate(isValid => {
        if (isValid) {
            getAskCode(emailForm.email, coldTime, 'modify')
        }
    })
}

function modifyEmail() {
    emailFormRef.value.validate(isValid => {
        if (isValid) {
            userModifyEmail(emailForm, () => {
                ElMessage.success('邮箱修改成功')
                store.user.email = emailForm.email
                emailForm.code = ''
            })
        }
    })
}

function beforeAvatarUpload(rawFile) {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('头像格式错误');
        return false
    } else if (rawFile.size / 1024 > 100) {
        ElMessage.error('头像大小不能超过100KB')
        return false
    }
    return true
}

function uploadSuccess(response) {
    ElMessage.success('头像上传成功')
    console.log(response)
    store.user.avatar = response.data.avatar
}

onMounted(() => {
    getUserDetail(data => {
        baseForm.username = store.user.username
        baseForm.desc = desc.value = data.desc
        Object.assign(baseForm, data)
        emailForm.email = store.user.email
        loading.form = false
    })
})

</script>

<template>
    <div style="display: flex; max-width: 1080px; margin: auto">
        <div class="settings-left">
            <card :icon="User" title="账号信息" desc="编辑个人信息设置" v-loading="loading.form">
                <el-form :model="baseForm" :role="rules" ref="baseFormRef" label-position="top"
                         style="margin: 0 10px 10px 10px;">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="baseForm.username" maxlength="12"/>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="baseForm.gender">
                            <el-radio :label="0">男</el-radio>
                            <el-radio :label="1">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="baseForm.phone" maxlength="11"/>
                    </el-form-item>
                    <el-form-item label="QQ" prop="qq">
                        <el-input v-model="baseForm.qq" maxlength="15"/>
                    </el-form-item>
                    <el-form-item label="WeChat" prop="wx">
                        <el-input v-model="baseForm.wx" maxlength="25"/>
                    </el-form-item>
                    <el-form-item label="简介" prop="desc">
                        <el-input v-model="baseForm.desc" type="textarea" :rows="5" maxlength="200"/>
                    </el-form-item>
                    <div>
                        <el-button :icon="Select" :loading="loading.base" @click="saveDetails" type="success">保存
                        </el-button>
                    </div>
                </el-form>
            </card>
            <card style="margin-top: 20px;" :icon="Message" title="电子邮件" desc="修改电子邮件">
                <el-form :model="emailForm" @validate="onValidate" :rules="rules" ref="emailFormRef"
                         label-position="top"
                         style="margin: 0 10px 10px 10px;">
                    <el-form-item label="电子邮件" prop="email">
                        <el-input v-model="emailForm.email"/>
                    </el-form-item>
                    <el-form-item prop="code">
                        <el-row style="width: 100%;" :gutter="10">
                            <el-col :span="18">
                                <el-input v-model="emailForm.code" placeholder="请获取验证码"/>
                            </el-col>
                            <el-col :span="6">
                                <el-button type="success" @click="sendEmailCode"
                                           :disabled="!isEmailValid || coldTime > 0"
                                           style="width: 100%;" plain>
                                    {{ coldTime > 0 ? `请等待 ${coldTime} 秒` : '获取验证码' }}
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <div>
                        <el-button :icon="Refresh" @click="modifyEmail" type="success">更新邮箱</el-button>
                    </div>
                </el-form>
            </card>
        </div>
        <div class="settings-right">
            <div style="position: sticky; top: 20px">
                <card>
                    <div style="text-align: center; padding: 2px 15px 0 15px">
                        <el-avatar :size="70" :src="store.avatarUrl"/>
                        <div style="margin: 5px 0">
                            <el-upload
                                    :action="axios.defaults.baseURL + '/api/image/avatar'"
                                    :show-file-list="false"
                                    :before-upload="beforeAvatarUpload"
                                    :on-success="uploadSuccess"
                                    :headers="accessHeader()"
                            >
                                <el-button size="small" round>修改头像</el-button>
                            </el-upload>
                        </div>
                        <div style="font-weight: bold">你好 {{ store.user.username }}</div>
                    </div>
                    <el-divider style="margin: 10px 0"/>
                    <div style="font-size: 14px; color: grey; padding: 10px">
                        {{ desc || '该用户尚未填写简介' }}
                    </div>
                </card>
                <card style="margin-top: 10px; font-size: 14px">
                    <div>
                        <span>注册时间: {{ registerTime }}</span>
                    </div>
                    <div style="color: grey;">
                        <span>欢迎加入我们的学习交流论坛</span>
                    </div>
                </card>
            </div>
        </div>
    </div>
</template>

<style scoped>
.settings-left {
    flex: 1;
    margin: 20px;
}

.settings-right {
    width: 300px;
    margin: 20px 30px 20px 0;
}
</style>